/*
 * @Author: 六弦(melodyWxy)
 * @Date: 2022-03-01 00:31:02
 * @LastEditors: 六弦(melodyWxy)
 * @LastEditTime: 2022-03-01 14:08:15
 * @FilePath: /menorepo-demo/Users/wxy/codeWorks/up/d_form/antd-demo-ts/src/components/XForm/index.tsx
 * @Description: update here
 */


import { Button } from 'antd';
import { formSet } from "./config";
import { FormItemSets, FormSets, ChildTypeSets, Btn } from "./type";

import type { FC } from "react";
import type { FormSchema, FormProps, FormItemProps, FormItem, Child } from "./type";


// 动态表单-渲染Item内部的Child
const renderItemChild = (child: Child) => {
    const { type, props } = child;
    
    const TargetChildComponent = formSet.get(type);
    const childProps = {
        ...props,
    }
    return (
        <TargetChildComponent {...childProps} />
    )

}

// 动态表单-渲染Items
const renderFromItems = (itemList: FormItem[] ) => {
    const items = itemList.map((item, index) => {
        const { type, name, props, child, required, message } = item;
        const TargetItemComponent = formSet.get(type);
        const itemProps = {
            name,
            rules: [] as Record<any, any>,
            ...props,
            valuePropName: 'value'
        }
        if(required){
            itemProps.rules.push({
                required: true,
                message: message || '这是一个必填项!',
            })
        }
        switch(child.type){
            case ChildTypeSets.Checkbox:
                itemProps.valuePropName="checked";
                break;
            default:
                break;
        }
       
        return (
            <TargetItemComponent key={index} {...itemProps}>
                {renderItemChild(child)}
            </TargetItemComponent>
        )
    })
    return items;

}

// 渲染按钮
const renderBtns = (btns: Btn[]) => {
    const btnList = btns.map((item, index)=> {
        const { wrapProps, type, props, text, submit } = item;
        const Item = formSet.get(FormItemSets.Item);
        const btnProps = {
            type,
            ...props,
        } as Record<any, any>
        if(submit){
            btnProps.htmlType="submit";
        }
        return (
            <Item key={index} {...wrapProps} >
                <Button {...btnProps} > {text} </Button>
            </Item>
        )
    })
    return btnList;
}


// 动态表单组件
const XForm: FC<{ schema: FormSchema }> = ({ schema }) => {
    const {type, props, onFinish, children, btns, title } = schema;
    const TargetForm = formSet.get(type);
    const formProps = {
        labelCol: {
            span: 8,
        },
        wrapperCol:{
            span: 16,
        },
        ...props,
        onFinish
    }
    return (
        <>
            {title && <h3>title</h3>}
            <TargetForm {...formProps}>
                {renderFromItems(children)}
                {renderBtns(btns)}
            </TargetForm>
      </>
    );
};
export default XForm;
